package com.somg.disruptor_study.demo01;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.somg.disruptor_study.demo01.longevent.LongEvent;
import com.somg.disruptor_study.demo01.longevent.LongEventFactory;
import com.somg.disruptor_study.demo01.longevent.LongEventHandler;
import com.somg.disruptor_study.demo01.stringevent.StringEvent;
import com.somg.disruptor_study.demo01.stringevent.StringEventFactory;
import com.somg.disruptor_study.demo01.stringevent.StringEventHandler;

public class DisruptorMain {
	
	
	
	public static void main(String[] args) {
		
		Disruptor sdisruptor = stringMethod();
		Disruptor ldisruptor = longMethod(sdisruptor);
		
		
		RingBuffer<LongEvent> ringbuf = ldisruptor.getRingBuffer();
		long sequence = ringbuf.next();
	try{
		LongEvent event = ringbuf.get(sequence);
		long data = 234;
		event.setValue(data);
	}finally{
		ringbuf.publish(sequence);
	}
		
//		disruptor.shutdown();
//		executor.shutdown();
		
	}
	
	
	public static Disruptor longMethod(Disruptor disruptor)
	{
		ExecutorService executor = Executors.newCachedThreadPool();
		
		EventFactory<LongEvent> eventFactory = new LongEventFactory();
		int ringBufferSize = 1024* 1024;
		
		Disruptor<LongEvent> longdisruptor = new Disruptor<LongEvent>(eventFactory, ringBufferSize, executor);
		
		LongEventHandler eventHandler = new LongEventHandler();
		eventHandler.setDisruptor(disruptor);
		longdisruptor.handleEventsWith(eventHandler);
		longdisruptor.start();
		return longdisruptor;
	}
	
	public static Disruptor stringMethod()
	{
		ExecutorService executor = Executors.newCachedThreadPool();
		
		EventFactory<StringEvent> eventFactory = new StringEventFactory();
		int ringBufferSize = 1024* 1024;
		
		Disruptor<StringEvent> Stringdisruptor = new Disruptor<StringEvent>(eventFactory, ringBufferSize, executor);
		
		EventHandler<StringEvent> eventHandler = new StringEventHandler();
		Stringdisruptor.handleEventsWith(eventHandler);
		Stringdisruptor.start();
		return Stringdisruptor;
	}
}
